/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import models.GroupModel;

/**

 * @author sochy
 */
public class Groups extends javax.swing.JFrame {

    /**
     * Creates new form Groups
     */
    GroupModel db;        // obj data type as class 'GroupModel'  !!!!           
    DefaultTableModel model;

    public Groups() {
        initComponents();         // defualt method , it regenerate when we create  UI  in the GUI editor ..... (kom kvol )
        // Load model
        db = new GroupModel();   // create obj name 'db',  from class GroupModel // used to connect database !!!  and have 6 abstract method  {select , insert , delect, update, delect, close}
        // Ini table object
        model = (DefaultTableModel) tbl_group.getModel();
        // Reload data in table
        this.reloadData();

        // Set button disable
        this.btnSave.setEnabled(false);
        this.btnDelete.setEnabled(false);
        this.btnUpdate.setEnabled(false);

    }

    /**
     * Load data from database table to fill on JTable
     */
    public void reloadData() {
        try {
            model.setRowCount(0);
            String sql = "SELECT * FROM groups";
            ResultSet rs = db.select(sql);

            while (rs.next()) {
                
                int id = rs.getInt("gro_id");
                String name = rs.getString("gro_name");
                String des = rs.getString("gro_des");
                // Add row to table interface
                Object[] rowData = new Object[]{id, name, des};
                model.addRow(rowData);
            }
            db.close();

        } catch (SQLException ex) {
            Logger.getLogger(Groups.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void clearForm() {
        this.id.setText("");
        this.name.setText("");
        this.description.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        group_form_panel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        id = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        name = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        description = new javax.swing.JTextArea();
        btnSave = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnNew = new javax.swing.JButton();
        group_list_panel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbl_group = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Manage user group");

        group_form_panel.setBorder(javax.swing.BorderFactory.createTitledBorder("User group form"));
        group_form_panel.setName(""); // NOI18N

        jLabel1.setText("ID");

        id.setEditable(false);

        jLabel2.setText("Group name(*)");

        name.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameActionPerformed(evt);
            }
        });

        jLabel3.setText("Description");

        description.setColumns(20);
        description.setRows(5);
        jScrollPane2.setViewportView(description);

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnNew.setText("New");
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout group_form_panelLayout = new javax.swing.GroupLayout(group_form_panel);
        group_form_panel.setLayout(group_form_panelLayout);
        group_form_panelLayout.setHorizontalGroup(
            group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(group_form_panelLayout.createSequentialGroup()
                .addGroup(group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(group_form_panelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(id)
                            .addComponent(name)
                            .addGroup(group_form_panelLayout.createSequentialGroup()
                                .addGroup(group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, group_form_panelLayout.createSequentialGroup()
                        .addGap(0, 12, Short.MAX_VALUE)
                        .addComponent(btnNew)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDelete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSave)))
                .addContainerGap())
        );
        group_form_panelLayout.setVerticalGroup(
            group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(group_form_panelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(group_form_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnUpdate)
                    .addComponent(btnDelete)
                    .addComponent(btnNew))
                .addContainerGap(121, Short.MAX_VALUE))
        );

        group_list_panel.setBorder(javax.swing.BorderFactory.createTitledBorder("User group list"));

        tbl_group.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Description"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbl_group.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tbl_group.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbl_groupMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tbl_group);

        javax.swing.GroupLayout group_list_panelLayout = new javax.swing.GroupLayout(group_list_panel);
        group_list_panel.setLayout(group_list_panelLayout);
        group_list_panelLayout.setHorizontalGroup(
            group_list_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)
        );
        group_list_panelLayout.setVerticalGroup(
            group_list_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(group_list_panelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 397, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(group_form_panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(group_list_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(group_list_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(group_form_panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nameActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        String name = this.name.getText();
        String description = this.description.getText();
        String sql = "INSERT INTO groups (gro_name, gro_des) VALUES('" + name + "','" + description + "')";
       
        // insert data into database
        this.db.insert(sql);
        // Close database connection
        this.db.close();
        // Reload data for jTable after click save button
        this.reloadData();
        // Clear Form
        this.clearForm();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void tbl_groupMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_groupMousePressed
        // TODO add your handling code here:

        // Get data from selected row
        int selected_row = tbl_group.getSelectedRow();
        String id = model.getValueAt(selected_row, 0).toString();
        System.out.println(id);
        String name = (String) model.getValueAt(selected_row, 1);
        String description = (String) model.getValueAt(selected_row, 2);
        // Fill data to form
        this.id.setText(id);
        this.name.setText(name);
        this.description.setText(description);
        
        this.btnSave.setEnabled(false);
        this.btnDelete.setEnabled(true);
        this.btnUpdate.setEnabled(true);
    }//GEN-LAST:event_tbl_groupMousePressed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        // TODO add your handling code here:
        this.clearForm();
        this.btnSave.setEnabled(true);
        this.btnDelete.setEnabled(false);
        this.btnUpdate.setEnabled(false);
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        // TODO add your handling code here:

        int id = Integer.parseInt(this.id.getText());
        String name = this.name.getText();
        String description = this.description.getText();
        String sql = "UPDATE groups set gro_name='" + name + "', gro_des='" + description + "' WHERE gro_id=" + id;
        this.db.update(sql);
        this.reloadData();
        this.clearForm();

        // Disable button
        this.btnSave.setEnabled(false);
        this.btnDelete.setEnabled(false);
        this.btnUpdate.setEnabled(false);


    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this item?") == JOptionPane.OK_OPTION) {
            int id = Integer.parseInt(this.id.getText());
            String sql = "DELETE FROM groups WHERE gro_id=" + id;
            this.db.delete(sql);
            this.reloadData();
            this.clearForm();
            // Disable button
            this.btnSave.setEnabled(false);
            this.btnDelete.setEnabled(false);
            this.btnUpdate.setEnabled(false);
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Groups.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Groups.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Groups.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Groups.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Groups().setVisible(true);
            }
        });
        //</editor-fold>
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JTextArea description;
    private javax.swing.JPanel group_form_panel;
    private javax.swing.JPanel group_list_panel;
    private javax.swing.JTextField id;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField name;
    private javax.swing.JTable tbl_group;
    // End of variables declaration//GEN-END:variables
}
